﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace seo.util
{
    public class HttpHelper
    {
        CookieContainer CookieJar = new CookieContainer();
        HttpWebResponse HttpWResponse;

        public string GetPage(string posturl, string postData)
        {
            //postData = "langpair=en|zh-CN&text=a%0D%0Aa";
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
            byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "text/html";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

        bool MakeWebRequest(Uri URL, string Method)
        {
            // this function will try to make a connection and then fill out the 
            // different controls with their correct values based on the request
            // it will return a false if it fails.

            // declare a WebProxy class object to use.

            //try catch block to catch any errors
            try
            {

                //Create a new request
                HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(URL);
                // set the HttpWebRequest objects cookie container
                // if you have any cookies that you want to go with the request you can add them 
                // to the cookiecontainer. If you had made a previous request that returned any cookies
                // that needed to be sent on subsequent request this will make sure that they are sent. 
                HttpWRequest.CookieContainer = CookieJar;

                // the default credentials are usually the Windows credentials (user name, password, and domain) of the user running the application                    
                HttpWRequest.Credentials = CredentialCache.DefaultCredentials;

                // set the name of the user agent. This is the client name that is passed to IIS
                // HttpWRequest.UserAgent = "CSharp HTTP Sample";
                // set the connection keep-alive
                HttpWRequest.KeepAlive = true; //this is the default
                //we don't want caching to take place so we need
                // to set the pragma header to say we don't want caching
                HttpWRequest.Headers.Set("Pragma", "no-cache");
                //set the request timeout to 5 min.
                HttpWRequest.Timeout = 300000;
                // set the request method
                HttpWRequest.Method = Method;

                //check to see if we have previously created a response object
                if (null != HttpWResponse)
                {
                    HttpWResponse.Close(); // close any previous connection
                    HttpWResponse = null; // clear the object. 
                }
                //get the response. This is where we make the connection to the server
                HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();

                // Get the Status code
                int iStatCode = (int)HttpWResponse.StatusCode;

                return true;
            }
            catch (WebException WebExcp)
            {
                Console.WriteLine(WebExcp.Message.ToString());
                //MessageBox.Show(WebExcp.Message.ToString());
                ICertificatePolicy CertPolicy = ServicePointManager.CertificatePolicy;

                return false;
            }
            catch (Exception e) // get any other error
            {
                Console.WriteLine(e.Message.ToString());
                //MessageBox.Show(e.Message.ToString());
                return false;
            }
        }

        public string sendRequest(string url)
        {
            string response = String.Empty;
            string sRequestType = "GET"; //default is GET
            Uri requestURL;

            //to do parse the URL to see if it has http or https if the in it
            //MessageBox.Show(sURL);
            string temp = url.ToLower();

            try
            {
                requestURL = new Uri(url);
            }
            catch (UriFormatException UriExcp)
            {
                Console.WriteLine(UriExcp.Message.ToString());
                //MessageBox.Show(UriExcp.Message.ToString());
                return response;
            }


            //Call a function that does the work to get the request.
            if (!MakeWebRequest(requestURL, sRequestType))
            {
                return response; // the call failed
            }

            //we want to enable and disable some buttons.

            Stream stream = HttpWResponse.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.UTF8);
            //Convert the stream to a string
            string s = sr.ReadToEnd();
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<meta[^>]*?charset=\s*?([^\s""']+).*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Match match = regex.Match(s);
            string charset = "UTF-8";
            if (match.Success) charset = match.Groups[1].Value;            
            sr.Close();

            if (!MakeWebRequest(requestURL, sRequestType))
            {
                return response; // the call failed
            }
            stream = HttpWResponse.GetResponseStream();
            sr = new StreamReader(stream, Encoding.GetEncoding(charset));
            response = sr.ReadToEnd();
            sr.Close();
            return response;
        }
    }
}
